<template>

    <div class="message-center-page">
        <div>
            <!-- 页面标题 -->
            <page-header :showBackText="true" backText="返回" backIconColor="#108EE9" title="消息" titleColor="#333333"
                placeholderText="返回" />
            <!-- 1. 顶部标签页 -->
            <top-tab :hasUnreadActivityMessages="hasUnreadActivityMessages"
                :hasUnreadOrderMessages="hasUnreadOrderMessages" :activeTab="activeTab" @switchTab="switchTab" />
            <!-- 2. 操作栏 -->
            <actions-bar @deleteAllRead="deleteAllRead" @markAllAsRead="markAllAsRead" />
        </div>

        <!-- 3. 消息列表 -->
        <main class="message-list">
            <van-list v-model:loading="loading" :finished="!hasMore"
                :finished-text="currentMessages.length === 0 ? '' : '没有更多了'" @load="loadMore">
                <template v-if="currentMessages.length > 0">
                    <swipe-message-item v-for="message in currentMessages" :key="message.id" :message="message"
                        :ref="el => (messageItemRefs[message.id] = el)" @mark-read="handleMarkRead"
                        @delete="handleDeleteRequest" @swipe-start="handleSwipeStart" />
                </template>
            </van-list>
            <div v-if="currentMessages.length === 0 && !loading" class="empty-state">
                <div class="empty-icon-placeholder"></div>
                <p>暂无消息</p>
            </div>
        </main>
        <!-- 4. 删除确认对话框 -->
        <confirm-dialog :visible="isDialogVisible" @confirm="confirmDelete" @cancel="isDialogVisible = false" />
        <!-- 5. 奖励提示 -->
        <reward-toast v-model="showRewardToast" :message="rewardAmount" />

    </div>
</template>

<script setup lang="ts">
import { ref, computed, onBeforeUpdate, onMounted } from 'vue';
import SwipeMessageItem from './components/SwipeMessageItem.vue';
import type { Message } from './data';
import TopTab from './components/TopTab.vue';
import ActionsBar from './components/ActionsBar.vue';
import ConfirmDialog from './components/ConfirmDialog.vue';
import PageHeader from '@/components/PageHeader.vue';
import RewardToast from '@/components/RewardToast.vue';
// --- 数据模拟 ---
import { storeToRefs } from 'pinia'
import { useMessageStore } from '@/stores/message';
// 使用 store
const messageStore = useMessageStore();
const { allActivityMessages, allOrderMessages } = storeToRefs(messageStore)
const activityMessages = ref<Message[]>([]);
const orderMessages = ref<Message[]>([]);
import { useGoldCoinStore } from '@/stores/goldCoins'
const goldCoinStore = useGoldCoinStore()
const { goldCoins } = storeToRefs(goldCoinStore)


// --- 状态管理 ---
const activeTab = ref<'activity' | 'order'>('activity');
const isDialogVisible = ref(false);
const messageIdToDelete = ref<number | null>(null);
const messageItemRefs = ref<Record<number, any>>({});
const currentPage = ref(1);
const pageSize = ref(6);
const loading = ref(false);
const hasMore = ref(true);
// 控制奖励提示的显示和内容
const showRewardToast = ref(false);
const rewardAmount = ref(0);

onBeforeUpdate(() => {
    messageItemRefs.value = {}; // 每次更新前清空 refs，防止内存泄漏
});

// 检查是否有未读活动消息
const hasUnreadActivityMessages = computed(() => {
    return allActivityMessages.value.some(message => !message.read);
});

// 检查是否有未读订单消息
const hasUnreadOrderMessages = computed(() => {
    return allOrderMessages.value.some(message => !message.read);
});
// 计算当前显示的列表位置
const currentMessages = computed(() => {
    return activeTab.value === 'activity' ? activityMessages.value : orderMessages.value;
});

// 切换标签页
const switchTab = (tab: 'activity' | 'order') => {
    activeTab.value = tab;
    currentPage.value = 1;
    hasMore.value = true;
    loadData();
};

// 初始化加载数据
const loadData = () => {
    const sourceData = activeTab.value === 'activity' ? allActivityMessages.value : allOrderMessages.value;
    const targetData = activeTab.value === 'activity' ? activityMessages : orderMessages;

    // 重置数据
    targetData.value = [];

    // 加载第一页数据
    const firstPageData = sourceData.slice(0, pageSize.value);
    targetData.value = firstPageData;

    // 检查是否有更多数据
    hasMore.value = sourceData.length > pageSize.value;

    // 更新当前页码为1（第一页已加载完成）
    currentPage.value = 1;
};

// 加载更多数据
const loadMore = () => {
    if (!hasMore.value || !loading.value) return;
    // 模拟网络请求延迟
    setTimeout(() => {
        try {
            const sourceData = activeTab.value === 'activity' ? allActivityMessages.value : allOrderMessages.value;
            const targetData = activeTab.value === 'activity' ? activityMessages : orderMessages;

            // 计算下一页的起始索引
            const startIndex = currentPage.value * pageSize.value;
            const endIndex = startIndex + pageSize.value;

            // 获取下一页数据
            const nextPageData = sourceData.slice(startIndex, endIndex);

            // 如果有数据才添加
            if (nextPageData.length > 0) {
                targetData.value = [...targetData.value, ...nextPageData];
            }

            // 更新页码和是否还有更多数据
            currentPage.value++;
            hasMore.value = endIndex < sourceData.length;
        } catch (error) {
            console.error('加载更多数据失败:', error);
        } finally {
            // 确保无论如何loading都会被重置为false
            loading.value = false;
        }
    }, 1500);
};

// 核心逻辑：当一个 item 开始滑动时，关闭所有其他已打开的 item
const handleSwipeStart = (swipedItemId: number) => {
    // 先关闭所有已打开的 item
    Object.keys(messageItemRefs.value).forEach(id => {
        if (Number(id) !== swipedItemId) {
            messageItemRefs.value[Number(id)]?.close();
        }
    });
};
// 标记为已读+显示奖励提示
const handleMarkRead = (id: number) => {
    console.log(`标记为已读: ${id}`);
    // 更新源数据
    const sourceList = activeTab.value === 'activity' ? allActivityMessages.value : allOrderMessages.value;
    const sourceMsg = sourceList.find(m => m.id === id);
    console.log(sourceMsg);
    // 检查是否有获得租币的消息，如果有则提取数量并显示奖励提示
    if (sourceMsg && sourceMsg.subtitle && !sourceMsg.read) {
        const coinMatch = sourceMsg.subtitle.match(/((获得)|(赠送))(\d+)个租币/);
        if (coinMatch && coinMatch[4]) {
            rewardAmount.value = Number(coinMatch[4]);
            goldCoins.value += Number(coinMatch[4]);
            showRewardToast.value = true;

            // 1.5秒后自动隐藏奖励提示
            setTimeout(() => {
                showRewardToast.value = false;
            }, 1500);
        }
    }
    if (sourceMsg) sourceMsg.read = true;

    // 更新当前显示的数据
    // const displayMsg = currentMessages.value.find(m => m.id === id);

    // if (displayMsg) displayMsg.read = true;

    // 自动关闭滑动项，使其返回到初始位置
    if (messageItemRefs.value[id]) {
        messageItemRefs.value[id].close();
    }
};
// 提交删除消息
const handleDeleteRequest = (id: number) => {
    messageIdToDelete.value = id;
    isDialogVisible.value = true;
};
// 执行确认删除
const confirmDelete = () => {
    if (messageIdToDelete.value === null) return;

    // 从源数据中删除
    const sourceList = activeTab.value === 'activity' ? allActivityMessages : allOrderMessages;
    sourceList.value = sourceList.value.filter(m => m.id !== messageIdToDelete.value);

    // 重新加载当前页数据
    loadData();

    isDialogVisible.value = false;
    messageIdToDelete.value = null;
};

// 一键已读功能
const markAllAsRead = () => {
    const sourceList = activeTab.value === 'activity' ? allActivityMessages.value : allOrderMessages.value;

    // 更新源数据
    sourceList.forEach(message => {
        const coinMatch = message.subtitle.match(/((获得)|(赠送))(\d+)个租币/);
        if (coinMatch && coinMatch[4] && !message.read) {
            goldCoins.value += Number(coinMatch[4]);
        }
        message.read = true;
    });

    // 更新当前显示的数据
    // currentMessages.value.forEach(message => {
    //     message.read = true;
    // });
};

// 一键删除已读功能
const deleteAllRead = () => {
    const sourceList = activeTab.value === 'activity' ? allActivityMessages : allOrderMessages;
    // 在源数据中删除已读消息
    sourceList.value = sourceList.value.filter(m => !m.read);
    loadData();
};

// 组件挂载时加载数据
onMounted(() => {
    loadData();
});
</script>

<style lang="scss" scoped>
$primary-color: #1abc9c;

.message-center-page {
    height: 100vh;
    background-color: #f7f8fa;
    display: flex;
    flex-direction: column;

    .message-list {
        flex: 1;
        overflow-y: auto;

        .list-footer,
        .empty-state {
            text-align: center;
            padding: 30px;
            color: #ccc;
        }

        .empty-state {
            padding-top: 80px;

            p {
                font-family: PingFangSC, PingFang SC;
                font-weight: 400;
                font-size: 17px;
                color: #999999;
                line-height: 17px;
                text-align: center;
                font-style: normal;
            }

            .empty-icon-placeholder {
                width: 142px;
                height: 120px;
                margin: 0 auto 15px;
                background-image: url('@/assets/messageImg/编组@2x.webp');
                background-size: 100% 100%;
                background-position: center;
                background-repeat: no-repeat;

            }
        }
    }
}
</style>